package com.blueocean_health.care.management.service.impl;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blueocean_health.care.management.common.base.id.IdUtils;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.domain.base.OrderInfo;
import com.blueocean_health.care.management.domain.dto.OrderRefundLklReqDto;
import com.blueocean_health.care.management.domain.dto.OrderRefundReqDto;
import com.blueocean_health.care.management.domain.dto.PayInfoListDto;
import com.blueocean_health.care.management.domain.dto.PayInfoReportDto;
import com.blueocean_health.care.management.domain.dto.PayInfoReqDto;
import com.blueocean_health.care.management.domain.ordervo.LklProVo;
import com.blueocean_health.care.management.domain.ordervo.OrderRefundVo;
import com.blueocean_health.care.management.em.AccountFlagEnum;
import com.blueocean_health.care.management.em.OrderStatusEnum;
import com.blueocean_health.care.management.em.OrderTypeEnum;
import com.blueocean_health.care.management.em.PayStatusEnum;
import com.blueocean_health.care.management.em.RefundStatusEnum;
import com.blueocean_health.care.management.mapper.OrderPayInfoMapper;
import com.blueocean_health.care.management.service.IOrderPayService;
import com.blueocean_health.care.management.service.IOrderSelectService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import lombok.extern.slf4j.Slf4j;

@Service
public class OrderPayServiceImpl implements IOrderPayService {

	private static Logger log = Logger.getLogger(OrderPayServiceImpl.class);
	@Resource
	private OrderPayInfoMapper orderPayMapper;
	@Resource
	private LklProVo lklProVo;
	@Autowired
	RestTemplate restTemplate;
	@Resource
	private IOrderSelectService orderSelectService;

	@Override
	public Page<PayInfoListDto> listRecord(PayInfoReqDto dto) {
		PageHelper.startPage(dto.getPage(), dto.getPageSize());
		List<PayInfoListDto> list = orderPayMapper.list(dto);
		Page<PayInfoListDto> pageList = (Page<PayInfoListDto>) list;
		return pageList;
	}

	@Override
	public void updateLashStatus(PayInfoReqDto dto) {
		orderPayMapper.updateLashStatus(dto.getIds(), dto.getIsLash());
	}

	@Override
	public List<PayInfoReportDto> exportRecord(PayInfoReqDto dto) {
		List<PayInfoReportDto> list = orderPayMapper.exportList(dto);
		return list;
	}

	/**
	 * 确认退款
	 */
	@Override
	public void refundDo(OrderRefundReqDto dto) {
		// 根据退款订单号查原订单号
		OrderInfo info = orderSelectService.selectOrderByorderid(dto.getOrderId());
		if (info == null || StringUtils.isEmpty(info.getRefundOrderId())) {
			throw new RuntimeException("无此订单，请检查后重试！");
		}
		// 根据原订单号查询付款信息
		OrderRefundVo refundInfo = orderPayMapper.getByOrderId(info.getRefundOrderId());
		if (refundInfo == null) {
			throw new RuntimeException("此订单无付款信息，请检查后重试！");
		}
		refundInfo.setHospitalId(info.getHospitalId());
		// 接收传入金额
		refundInfo.setAmount(dto.getAmount());
		refundInfo.setReqLogNo(IdUtils.getRandomIdByDateTime());// 生成退款流水号
		refundInfo.setOrderType(OrderTypeEnum._3.getKey());
		refundInfo.setOrderId(dto.getOrderId());//设置退款单号
		OrderRefundLklReqDto req = new OrderRefundLklReqDto(lklProVo.getAppName(), lklProVo.getAppKey(),
				lklProVo.getAppSecret(), refundInfo);
		// 请求拉卡拉退款服务
		JSONObject tokenObj = JSON.parseObject(restTemplate.postForObject(lklProVo.getRefundUrl(), req, String.class));
		log.info("请求拉卡拉退款服务url:" + lklProVo.getRefundUrl() + " 参数:{}" + req+",结果："+tokenObj);
		if ("0".equals(tokenObj.getString("code"))) {// 退款成功
			dealAfterRefund(refundInfo);
		} else {
			throw new RuntimeException(tokenObj.getString("msg"));
		}
	}

	/**
	 * 退款后处理
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	private void dealAfterRefund(OrderRefundVo refundInfo) {
		// 添加退款对账单
		orderPayMapper.add(refundInfo);
		// 修改订单状态
		orderSelectService.changeOnlineOrderStatusStatus(refundInfo.getOrderId(), OrderStatusEnum._7, AccountFlagEnum._1,
				PayStatusEnum._3);
		// 修改收据表退款状态
		orderSelectService.updateRefundStatus(refundInfo.getOrderId(), RefundStatusEnum._2.getKey());
	}

}
